package com.ihg.hiex.admin.web.controller.session;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.ihg.hiex.admin.entity.security.Login;
import com.ihg.hiex.admin.service.account.DelegateService;
import com.ihg.hiex.admin.service.session.SessionDuringService;
import com.ihg.hiex.admin.service.session.SessionService;
import com.ihg.hiex.admin.web.resolver.Secure;
import com.ihg.hiex.admin.web.view.ExcelTemplateView;
import com.ihg.hiex.entity.session.Session;
import com.ihg.hiex.entity.session.Status;
import com.ihg.hiex.entity.session.during.SessionCalibration;
import com.ihg.hiex.entity.session.during.SessionCalibrationCompetency;
import com.ihg.hiex.entity.session.during.SessionCalibrationStatus;
import com.ihg.hiex.entity.session.during.report.SessionReportWriting;
import com.ihg.hiex.entity.user.Delegate;

/**
 * 
 * @author Guangli Yan
 *
 */
@Controller
@RequestMapping("")
@MenuSetting("menu-sessions")
public class SessionController {
    
    private static final Logger logger = LoggerFactory.getLogger(SessionController.class);
    
    @Autowired
    private SessionService sessionService;
    
    @Autowired
    private DelegateService delegateService;
    
    @Autowired
    private SessionDuringService sessionDuringService;
    
    /**
     * list all active session
     * 
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "/active-sessions", method = RequestMethod.GET)
    @MenuSetting("submenu-active-sessions-management")
    public ModelAndView list(Page page, HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("session/session-admin-list");
        
        int totals = sessionService.count(Status.ACTIVE);
        if (totals > 0) {

            List<Session> sessions = sessionService.list(Status.ACTIVE, page.with(totals));

            modelAndView.addObject("sessions", sessions);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }

        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @return
     */
    @RequestMapping(value = "/coach-sessions", method = RequestMethod.GET)
    @MenuSetting("submenu-coach-sessions-management")
    public ModelAndView listCoachSession(@Secure Login login) {
        
        ModelAndView modelAndView = new ModelAndView("session/session-coach-list");
        
        List<Delegate> delegates = delegateService.list(login.getId());
        List<Session> sessions = sessionService.list(delegates);
        modelAndView.addObject("sessions", sessions);

        return modelAndView;
        
    }
    
    /**
     * end view.
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/active-sessions/{id}/close", method = RequestMethod.GET)
    public ModelAndView close(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("session/session-close");
        
        modelAndView.addObject("id", id);

        return modelAndView;
        
    }

    /**
     * 
     * @param login
     * @param id
     * @return
     */
    @RequestMapping(value = "/active-sessions/{id}/close", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onClose(@Secure Login login, @PathVariable("id") Long id) {

        HttpResult httpResult = new HttpResult();

        try {
            
            Session session = sessionService.load(id);
            
            sessionService.close(session, login.getId(), login.getName());
        
            httpResult.success().message("结束成功");

        } catch (Exception e) {
            httpResult.fail("500").message("结束失败");
            logger.error("#onClose() - close session fail, exception is [{}]", e);
        }

        return httpResult;
        
    }
    
    /**
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/active-sessions/report-data-export", method = RequestMethod.GET)
    public ModelAndView onExport() {
        
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("active-session-report-data.xls", true));
        
        // list all active session's sessionReportWriting
        List<SessionReportWriting> sessionReportWritings = sessionDuringService.listSessionReportWriting(Status.ACTIVE, SessionCalibrationStatus.FINISH);
        modelAndView.addObject("reportWritings", CollectionUtils.constructMapValue(sessionReportWritings, "sessionCalibration.id"));
        
        List<SessionCalibration> sessionCalibrations = new ArrayList<SessionCalibration>();
        // list sessionCalibration by delegates
        if(!sessionReportWritings.isEmpty()) {
            sessionCalibrations = CollectionUtils.extractPropertyList(sessionReportWritings, "sessionCalibration");
            
            // list sessionCalibrationCompetency key->competencyName->sessionCalibrationId
            Map<String, List<SessionCalibrationCompetency>> competencies = sessionDuringService.listCalibrationCompetency(sessionCalibrations);
            modelAndView.addObject("competencies", competencies);
        }
        
        modelAndView.addObject("sessionCalibrations", sessionCalibrations);
        
        String[] competencyNames = new String[]{"Drive Result", "Work Collaboratively", "Champion Change", "Owner Relations", "Lead and Develop", "Financial Management", "Operations Management", "Revenue Maximisation"};
        modelAndView.addObject("competencyNames", competencyNames);
        
        return modelAndView;
        
    }
    
}